package pers.netty.chat.server;

import pers.netty.chat.common.codec.ProtobufDecoder;
import pers.netty.chat.common.codec.ProtobufEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

/**
 * @author 李醴茝
 */
@Slf4j
@Service
public class ChatServer {

    @Value("${server.port}")
    private int port;

    @Value("${server.address}")
    private String ipAddress;

    private static EventLoopGroup parentGroup = new NioEventLoopGroup();
    private static EventLoopGroup childGroup = new NioEventLoopGroup();
    private static ServerBootstrap b = new ServerBootstrap();

    @Autowired
    private ChatServerHandler serverHandler;

    @PostConstruct
    public void init() {
        run();
    }

    public void run() {
        try {
            b.group(parentGroup, childGroup);
            // 设置nio类型的channel
            b.channel(NioServerSocketChannel.class);
            // 设置监听端口
            b.localAddress(new InetSocketAddress(ipAddress, port));
            // 设置通道初始化
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                //有连接到达时会创建一个channel
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProtobufDecoder());
                    ch.pipeline().addLast(new ProtobufEncoder());
                    // pipeline管理channel中的Handler
                    // 在channel队列中添加一个handler来处理业务
                    ch.pipeline().addLast("serverHandler", serverHandler);
                }
            });
            // 配置完成，开始绑定server
            // 通过调用sync同步方法阻塞直到绑定成功
            ChannelFuture f = b.bind().sync();
            log.info("netty 服务端启动成功：" + f.channel().localAddress());
            // 监听服务器关闭事件
            // 应用程序会一直等待，直到channel关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("netty 服务端启动失败！", e);
        } finally {
            // 关闭EventLoopGroup，释放掉所有资源包括创建的线程
            parentGroup.shutdownGracefully();
            childGroup.shutdownGracefully();
        }
    }
}
